import React, { useState, useEffect } from 'react';
import { Card, Form, Space, Input, InputNumber, Switch, Button } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';

import ValueList from '@/components/ValueList';
import TipTitle from '@/components/TipTitle';
import { typeList } from '@/services/common';
import { otherConfigRules } from './validateRules';

const { Item: FormItem, List: FormList } = Form;
 
const OtherConfig: React.FunctionComponent<any> = (props) => {

  const [typeConfigList, setTypeConfigList] = useState(typeList);

  useEffect(() => {
    const actTypeConfigList = typeList.filter(t => !t.tag);
    setTypeConfigList(actTypeConfigList);
  }, []);

  // 获取下拉类型
  const getSelectType = (fieldPath: Array<string|number>|string) => {
    return props.form.getFieldValue(fieldPath) || 'string';
  };

  // 根据类型判断后续输入
  const getFormItemElement = (type: string) => {
    switch(type) {
      case 'string':
        return <Input />;
      case 'number':
        return <InputNumber style={{ width: '100%' }} precision={0} />;
      case 'boolean':
        return <Switch checkedChildren='是' unCheckedChildren='否' />;
      default:
        return <Input />;
    }
  }
    
  return (
    <Card title={<TipTitle title='拓展基础属性配置' tip='根据添加的属性名和属性值拼成拓展基础属性对放置于最终生成的DS文件中' />} className='other-ds-config-card'>
      <FormList name='dsConfigObj'>
        {(fields, { add, remove }) => (
          <>
            {fields.map((field: any, index: any) => (
              <Space key={field.key} align='baseline' style={{ paddingLeft: '3rem' }}>
                <FormItem {...field} label={`属性名${index + 1}`} name={[field.name, 'field']} rules={otherConfigRules.field}>
                  <Input />
                </FormItem>
                <FormItem {...field} label='属性类型' name={[field.name, 'type']}>
                  <ValueList options={typeConfigList} style={{ width: 120 }} />
                </FormItem>
                <FormItem shouldUpdate>
                  {() => {
                    const type = getSelectType(['dsConfigObj', index, 'type']);
                    return (
                      <FormItem {...field} label={`属性值${index + 1}`} name={[field.name, 'value']} valuePropName={type === 'boolean' ? 'checked' : undefined}>
                        {getFormItemElement(type)}
                      </FormItem>
                    )
                  }}
                </FormItem>
                <MinusCircleOutlined onClick={() => remove(field.name)} />
              </Space>
            ))}
            <FormItem>
              <Button type='dashed' onClick={() => add({ type: 'string' })} block icon={<PlusOutlined />}>
                基础属性配置
              </Button>
            </FormItem>
          </>
        )}
      </FormList>
    </Card>
  );
}
 
export default OtherConfig;
